package com.itheima.mq;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.RecommendVideo;
import com.itheima.domain.mongo.Video;
import com.itheima.util.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class RecommendVideoTask {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Scheduled(cron = "0/5 * * * * *")
    public void run() {
        Set<String> keys = stringRedisTemplate.keys(ConstantUtil.QUANZI_VIDEO + "*");
        if (CollectionUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                //获取当前登录用户
                Long userId = Long.valueOf(key.replaceAll(ConstantUtil.QUANZI_VIDEO, ""));
                //获取value
                String value = stringRedisTemplate.opsForValue().get(key);
                String[] vids = value.split(",");
                if (vids != null) {
                    Query query = new Query(Criteria.where("userId").is(userId));
                    mongoTemplate.remove(query, RecommendVideo.class);
                    for (String vid : vids) {
                        //根据vid查询动态信息
                        Query query1 = new Query(Criteria.where("vid").is(Long.valueOf(vid)));
                        Video video = mongoTemplate.findOne(query1, Video.class);
                        //System.out.println(video);
                        //构建推荐视频对象
                        RecommendVideo recommendVideo = new RecommendVideo();
                        recommendVideo.setDate(video.getCreated());
                        recommendVideo.setUserId(userId);
                        recommendVideo.setVid(Long.valueOf(vid));
                        recommendVideo.setScore(RandomUtil.randomDouble(66, 99));
                        recommendVideo.setVideoId(video.getId());
                        mongoTemplate.save(recommendVideo);
                    }
                }
            }
        }
    }
}
